package com.example.demo.demos.gateway;

public class GatewayCalculator {
    public static String calculateGateway(String ip, String subnetMask) {
        int ipInt = ipToInt(ip);
        int maskInt = ipToInt(subnetMask);
        int networkAddress = ipInt & maskInt;
        int gatewayAddress = networkAddress + 1; // 网关通常为网络地址+1
        return intToIp(gatewayAddress);
    }

    private static int ipToInt(String ip) {
        String[] segments = ip.split("\\.");
        return (Integer.parseInt(segments[0]) << 24) |
               (Integer.parseInt(segments[1]) << 16) |
               (Integer.parseInt(segments[2]) << 8) |
               Integer.parseInt(segments[3]);
    }

    private static String intToIp(int ip) {
        return String.format("%d.%d.%d.%d",
            (ip >> 24) & 0xFF, (ip >> 16) & 0xFF, 
            (ip >> 8) & 0xFF, ip & 0xFF);
    }
}